package com.lxd.sunso.product.service.impl;

import com.lxd.sunso.common.utils.PageUtils;
import com.lxd.sunso.common.utils.Query;
import com.lxd.sunso.product.entity.*;
import com.lxd.sunso.product.service.*;
import com.lxd.sunso.product.vo.ControlrealtimeVo;
import com.lxd.sunso.product.vo.MonitorDataVo;
import com.lxd.sunso.product.vo.RealDataVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxd.sunso.product.dao.ControlrealtimeDao;

import java.util.*;
import java.util.stream.Collectors;


@Service("controlrealtimeService")
public class ControlrealtimeServiceImpl extends ServiceImpl<ControlrealtimeDao, ControlrealtimeEntity> implements ControlrealtimeService {
    @Autowired
    private MachineService machineService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private DatatemplateService datatemplateService;

    @Autowired
    private TemplateService templateService;

    @Autowired
    private DatatypeService datatypeService;

    @Autowired
    private MachinekindService machinekindService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ControlrealtimeEntity> page = this.page(
                new Query<ControlrealtimeEntity>().getPage(params),
                new QueryWrapper<ControlrealtimeEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public RealDataVo listByCondition(Map<String, Object> params) {
        QueryWrapper<MachineEntity> queryWrapper = new QueryWrapper<>();
        String customerId = (String) params.get("customerId");
        Long templateId = null;
        if (!StringUtils.isEmpty((String) params.get("templateId"))) {
            templateId = Long.valueOf((String) params.get("templateId"));
        }

        String machineKind = (String) params.get("machineKind");
        String machineName = (String) params.get("machineName");

        if (!StringUtils.isEmpty(customerId)) {
            CustomerEntity customerEntity = customerService.getOne(new QueryWrapper<CustomerEntity>().eq("CustomerName", customerId));
            queryWrapper.eq("CustomerID", customerEntity.getId());
        }

        if (templateId != null) {
            queryWrapper.eq("TemplateID", templateId);
        }

        if (!StringUtils.isEmpty(machineKind)) {
            MachinekindEntity machinekindEntity = machinekindService.getOne(new QueryWrapper<MachinekindEntity>().eq("MachineNumber", machineKind));
            if (machinekindEntity != null) {
                queryWrapper.eq("MachineKind", machinekindEntity.getId());
            }
        }

        if (!StringUtils.isEmpty(machineName)) {
            queryWrapper.eq("MachineName", machineName);
        }

        //获取到所有符合条件的machine集合
        List<MachineEntity> machineEntities = machineService.list(queryWrapper);

        //对设备集合进行排序操作
        Collections.sort(machineEntities, (e1, e2) -> {
            if (e1.getIsonline().equals(e2.getIsonline())) {
                return e1.getMachinename().compareTo(e2.getMachinename());
            } else {
                return e2.getIsonline().compareTo(e1.getIsonline());
            }
        });

        //获取machine的Id集合
        List<Long> ids = machineEntities.stream().map(entity -> {
            Long machineId = entity.getId();
            return machineId;
        }).distinct().collect(Collectors.toList());


        //总记录数
        int totalcount = ids.size();

        //获取每页的数量以及当前页
        Integer size = Integer.valueOf((String) params.get("limit")); //每页的数量
        Integer page = Integer.valueOf((String) params.get("page"));//当前页

        //获取本次查询的machineId；起始索引：(page-1)*size,结束索引：page*size
        List<Long> machinelist = null;
        if (page * size < ids.size()) {
            machinelist = ids.subList((page - 1) * size, page * size);
        } else {
            machinelist = ids.subList((page - 1) * size, ids.size());
        }

        List<String> controlNames = datatemplateService.getControlNames(templateId);

        List<Map<String, String>> arrayList = new ArrayList<>();
        for (Long id : machinelist) {
            //创建每一行的结果集合,结果的内容要与表头一一对应
            //List<String> content = new ArrayList<>();
            MachineEntity machineEntity = machineService.getById(id);
            CustomerEntity customerEntity = customerService.getById(machineEntity.getCustomerid());
            //content.add(machineEntity.getMachinename()); //设备ID
            //content.add(machineEntity.getIsonline());    //设备的在线状态
            //后面存储数据
            List<String> dataAndUnit = this.getDataAndUnit(id.toString());
            String time = this.getTime(id);
            List<String> data = dataAndUnit.stream().map(entity -> {
                if (entity.contains("开/关")) {
                    String s = entity.replace("开/关", "");
                    if (s.contains("1"))
                        entity = "开";
                    else
                        entity = "关";
                }
                return entity;
            }).collect(Collectors.toList());

            Map<String, String> map = new HashMap<>();
            for (int i = 0; i < controlNames.size(); i++) {
                map.put(controlNames.get(i), data.get(i));
            }
            map.put("CustomerName", customerEntity.getCustomername());
            map.put("MachineName", machineEntity.getMachinename());
            map.put("IsOnline", machineEntity.getIsonline());
            map.put("OnTime", time);
            //获取所有实时数据中时间最接近的那一个
            arrayList.add(map);
        }

        RealDataVo realDataVo = new RealDataVo();
        realDataVo.setCurrPage((page));//当前页
        realDataVo.setTotalCount(Integer.valueOf(totalcount));//总条数
        realDataVo.setData(arrayList);
        realDataVo.setPageSize(size);
        return realDataVo;
    }

    /**
     * 根据模板的ID获取设备状态
     *
     * @param id
     * @return
     */
    @Override
    public ArrayList<HashMap<String, String>> listBytemplate(Integer id) {
        ArrayList<HashMap<String, String>> arrayList = new ArrayList<>();
        //根据传入的模板ID获取
        List<ControlrealtimeEntity> list = this.list(new QueryWrapper<ControlrealtimeEntity>().eq("TemplateId", id));
        List<Long> machineIdList = list.stream().map(entity -> {
                    Long machineid = entity.getMachineid();
                    return machineid;
                }
        ).distinct().collect(Collectors.toList());

        for (Long machineId : machineIdList) {
            HashMap<String, String> map = new HashMap<>();
            List<ControlrealtimeEntity> controlrealtimeEntities = this.list(new QueryWrapper<ControlrealtimeEntity>().eq("MachineId", machineId));
            controlrealtimeEntities.stream().map(entity -> {
                MachineEntity machineEntity = machineService.getById(entity.getMachineid());
                DatatemplateEntity datatemplateEntity = datatemplateService.getById(entity.getDatatemplateid());
                map.put("MachineName", machineEntity.getMachinename());
                map.put("IsOnline", machineEntity.getIsonline());
                map.put(datatemplateEntity.getControlname(), entity.getRealtimevalue());
                return entity;
            }).collect(Collectors.toList());
            arrayList.add(map);
        }
        return arrayList;
    }


    @Override
    public List<TemplateEntity> searchTemplate(String customerName) {
        ArrayList<TemplateEntity> entities = new ArrayList<>();
        CustomerEntity customerEntity = customerService.getOne(new QueryWrapper<CustomerEntity>().eq("CustomerName", customerName));
        if (customerEntity != null) {
            List<Long> list = machineService.findTemplateByCustomerId(customerEntity.getId());
            for (Long tempalteId : list) {
                TemplateEntity templateEntity = templateService.getById(tempalteId);
                entities.add(templateEntity);
            }
            return entities;
        }
        return null;
    }

    /**
     * 通过设备名称获取设备的所有信息
     *
     * @param machineName
     * @return
     */
    @Override
    public List<MonitorDataVo> listByMachine(String machineName) {
        MachineEntity machineEntity = machineService.getOne(new QueryWrapper<MachineEntity>().eq("MachineName", machineName));
        if (machineEntity != null) {
            List<DatatemplateEntity> datatemplateEntities = datatemplateService.list(new QueryWrapper<DatatemplateEntity>().eq("TemplateID", machineEntity.getTemplateid()));
            List<MonitorDataVo> collect = datatemplateEntities.stream().map(entity -> {
                ControlrealtimeEntity controlrealtimeEntity = this.getOne(new QueryWrapper<ControlrealtimeEntity>().eq("DataTemplateId", entity.getId()).eq("MachineId", machineEntity.getId()));
                MonitorDataVo monitorDataVo = new MonitorDataVo();
                BeanUtils.copyProperties(entity, monitorDataVo);
                if (entity.getUnitname().equals("开/关") && controlrealtimeEntity.getRealtimevalue().contains("1")) {
                    monitorDataVo.setRealTimeValue("开");
                } else if (entity.getUnitname().equals("开/关") && !controlrealtimeEntity.getRealtimevalue().contains("null")) {
                    monitorDataVo.setRealTimeValue("关");
                } else {
                    monitorDataVo.setRealTimeValue(controlrealtimeEntity.getRealtimevalue());
                }
                DatatypeEntity datatypeEntity = datatypeService.getById(entity.getDatatypeid());
                monitorDataVo.setDataTypeName(datatypeEntity.getDatatypename());
                monitorDataVo.setCreatetime(controlrealtimeEntity.getOntime());
                return monitorDataVo;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 根据设备型号获取可用的模板
     *
     * @param id
     * @return
     */
    @Override
    public List<TemplateEntity> searchTemplateByKind(Long id) {
        List<Long> list = machineService.searchTemplateByKind(id);
        List<TemplateEntity> templateEntities = (List<TemplateEntity>) templateService.listByIds(list);
        return templateEntities;
    }


    /**
     * 获取设备的实时数据拼接单位
     *
     * @param machineid
     * @return
     */
    @Override
    public List<String> getDataAndUnit(String machineid) {
        List<String> dataAndUnit = this.baseMapper.getDataAndUnit(machineid.toString());
        return dataAndUnit;
    }

    @Override
    public String getTime(Long machineid) {
        String time = this.baseMapper.getTime(machineid.toString());
        return time;
    }
}